package com.loft.model.renren.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.loft.comm.MyApp;
import com.loft.comm.util.LogCenter;
import com.loft.comm.util.MD5;

public class Connection {
	private final String TAG = this.getClass().getName();
	private String _jsonString;
	private HttpClient _httpClient;
	private HttpPost _httpPost;
	private HttpResponse _httpResponse;
	private List<NameValuePair> _paramList = new ArrayList<NameValuePair>();
	private Map<String, String> _systemParamMap;

	private void setSystemParamMap() {
		_systemParamMap = new HashMap<String, String>();
		_systemParamMap.put("v", "1.0");
		_systemParamMap.put("access_token", MyApp.RENREN_ACCESSTOKEN);
		_systemParamMap.put("format", "JSON");
	}

	private HttpPost getHttpPost(String apiPath) {
		return new HttpPost(apiPath);
	}

	private HttpClient getHttpClient() {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
		HttpConnectionParams.setSoTimeout(httpParams, 15000);
		return new DefaultHttpClient(httpParams);

	}

	private List<NameValuePair> getParamList(Map<String, String> parammap) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		List<String> keyList = new ArrayList<String>();
		Iterator<String> iterator = parammap.keySet().iterator();
		while (iterator.hasNext()) {
			keyList.add(iterator.next());
		}
		Collections.sort(keyList);
		for (int i = 0; i < parammap.size(); i++) {
			param.add(new BasicNameValuePair(keyList.get(i), parammap
					.get(keyList.get(i))));
		}
		return param;

	}

	private Map<String, String> getSigOk(Map<String, String> addParaMap) {
		Map<String, String> map = new HashMap<String, String>();
		map.putAll(_systemParamMap);
		map.putAll(addParaMap);
		List<String> keyList = new ArrayList<String>();
		Iterator<String> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			keyList.add(iterator.next());
		}
		Collections.sort(keyList);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < map.size(); i++) {
			sb.append(keyList.get(i) + "=" + map.get(keyList.get(i)));
			// "access_token=194218|6.1cee8c2799c11e0fc3fac3a04abd2042.2592000.1339750800-238204081
			// fields=uid,name,sex,star,zidou,vip,birthday,tinyurl,headurl,mainurl
			// ,hometown_location, work_history,university_history
			// format=JSON
			// method=users.getInfo
			// v=1.0
			// {secret_key}\"({secret_key}为你的Secret Key)"
		}
		sb.append(MyApp.RENREN_APPSECRET);// renren進行md5加密時需要在字符串末尾添加appsecret
		String sigtool = sb.toString();
		MD5 md5 = new MD5();
		String sig = md5.doMD5(sigtool);// renren很多api調用需要sig參數，該參數通過md5加密的方式得到
		LogCenter.getInstance().debugJSON(sig + "----------------->>>sig");
		map.put("sig", sig);
		return map;

	}

	public String connectionAndGetJsonString(Map<String, String> addParaMap) {
		setSystemParamMap();
		try {
			String apiPath = MyApp.RENREN_API;
			_httpPost = getHttpPost(apiPath);

			_httpClient = getHttpClient();

			Map<String, String> paramMap = getSigOk(addParaMap);
			_paramList = getParamList(paramMap);

			for (NameValuePair name : _paramList) {
				LogCenter.getInstance().debugJSON(name.toString());
			}

			_httpPost
					.setEntity(new UrlEncodedFormEntity(_paramList, HTTP.UTF_8));
			StringBuilder builder = new StringBuilder();
			_httpResponse = _httpClient.execute(_httpPost);
			HttpEntity entity = _httpResponse.getEntity();
			if (entity != null) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent()));
				String line = null;
				while ((line = reader.readLine()) != null) {
					builder.append(line + "\n");
				}
				reader.close();
			}
			_jsonString = builder.toString();
			LogCenter.getInstance().debugJSON(_jsonString);
			return _jsonString;
		} catch (Exception e) {
			LogCenter.getInstance().error(TAG, e.toString());
		}

		return null;
	}
}
